import React, { useEffect, useState } from 'react'
import { Button, Steps, Form, Input, Select, message, notification, Descriptions } from 'antd';
import newsAddStyle from './css/NewsAdd.less'
import { connect, useNavigate } from 'umi'
import NewsEditor from '@/components/NewsManage/NewsEditor';
import type { NotificationPlacement } from 'antd/es/notification/interface';

interface IFormInfo {
    title: string,
    categoryId: number
    categoryName?: string
}

function NewsAdd(props: any) {
    const { dispatch, categoriesList, editorText } = props;
    const navigate=useNavigate();
    const [categoriesOption, setCategoriesOption] = useState(categoriesList)
    // console.log(newsAddStyle)
    const [current, setCurrent] = useState(0);
    // 记录第一步的form表单的信息
    const [formInfo, setFormInfo] = useState<IFormInfo>({ title: '临时', categoryId: 1 })
    // 获取当前用户信息
    const currentUserData = JSON.parse(localStorage.getItem('token') as string)
    //#region 消息通知框
    const openNotification = (placement: NotificationPlacement, publishState: number) => {
        notification.open({
            message: `通知`,
            description: `你可以到${publishState === 0 ? '草稿箱' : '审核列表'}中查看您的新闻`,
            placement,
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    };
    //#endregion
    // 下一步点击回调事件
    const next = () => {
        if (current === 0) {
            form
                .validateFields()
                .then((values) => {
                    // console.log(values);
                    const categoryItem = categoriesList?.find((item: any) => item.id === values.categoryId);
                    values.categoryName = categoryItem.title;
                    setFormInfo(values);
                    setCurrent(current + 1);
                })
                .catch((info) => {
                    console.log('Validate Failed:', info);
                });
        }
        else if (current === 1) {
            console.log(editorText, formInfo);
            if ((editorText as string).trim() === '<p></p>') {
                message.error('请在编辑框输入内容！！')
            }
            else {
                setCurrent(current + 1);
                console.log(editorText, formInfo);
            }
        }
        else {
            setCurrent(current + 1);
        }
    };

    //上一步点击回调事件
    const prev = () => {
        setCurrent(current - 1);
    };
    //保存草稿 /提交审核 点击回调事件 auditState:0(草稿箱)，1(待审核)，2(已发布)，3(已下线)
    const handelSaveNews = (auditState: number) => {
        // console.log(htmlToDraft(editorText))
        const newsAddItem = {
            "title": formInfo.title,
            "categoryId": formInfo.categoryId,
            "content": editorText,
            "region": currentUserData && currentUserData?.length > 0 && currentUserData[0].region ? currentUserData[0].region : '全球',//区域
            "author": currentUserData && currentUserData?.length > 0 ? currentUserData[0].username : '临时工',
            "roleId": currentUserData && currentUserData?.length > 0 ? currentUserData[0].roleId : 3,//角色编号
            "auditState": auditState,//审核状态。初始为0
            "publishState": 0,//发布状态
            "createTime": Date.now(),    //创建时间
            "star": 0,  //点like次数
            "view": 0,  //观看次数
        }
        console.log(newsAddItem);
        dispatch({
            type: 'StandBox/addNewsList',
            payload: {
                newsItem: newsAddItem,
                auditState,
                navigate
            }
        })
        
        openNotification('bottomRight', auditState);
    };

    const stepItems = [
        {
            title: '基本信息',
            description: '新闻标题，新闻分类',
        },
        {
            title: '新闻内容',
            description: '新闻主题内容',
        },
        {
            title: '新闻提交',
            description: '保存草稿或者提交审核',
        },
    ];
    // 经 Form.useForm() 创建的 form 控制实例
    const [form] = Form.useForm();

    // selector选择框点击选择事件
    const handleSelectorChange = (value: any) => {
        console.log(value)
    }

    // 副作用函数，组件加载完毕后发布获取新闻分类的信息
    useEffect(() => {
        if ((categoriesList as Array<any>).length === 0) {
            dispatch({
                type: 'StandBox/getCategoriesList',
                payload: {}
            })
        }
        else {
            const newCategoriesList = categoriesList.map((item: any) => {
                item.label = item.title;
                item.value = item.id;
                return item
            });
            setCategoriesOption(newCategoriesList);
        }
    }, [categoriesList])
    return (
        <div>
            <h1 className={newsAddStyle.title}>撰写新闻</h1>
            <Steps
                current={current}
                items={stepItems}
            />
            <div className={newsAddStyle["steps-content"]}>
                <div className={current === 0 ? '' : newsAddStyle.hidden}>
                    <Form
                        name="basic"
                        labelCol={{ span: 2 }}
                        wrapperCol={{ span: 22 }}
                        form={form}
                        initialValues={{ categoryId: 1 }}
                    >
                        <Form.Item
                            label="新闻标题"
                            name="title"
                            rules={[{ required: true, message: '请输入新闻标题!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="新闻分类"
                            name="categoryId"
                            rules={[{ required: true, message: '请选择新闻分类!' }]}
                        >
                            <Select
                                onChange={handleSelectorChange}
                                options={categoriesOption}
                            />
                        </Form.Item>
                    </Form>
                </div>
                <div className={current === 1 ? '' : newsAddStyle.hidden}>
                    <NewsEditor myEditorType='add'></NewsEditor>
                </div>
                <div className={current === 2 ? '' : newsAddStyle.hidden}>
                    <Descriptions title="新闻信息" bordered column={2}>
                        <Descriptions.Item label="标题">{formInfo.title}</Descriptions.Item>
                        <Descriptions.Item label="文章类型"  contentStyle={{color:'orange'}}>{formInfo?.categoryName}</Descriptions.Item>
                        <Descriptions.Item label="文章内容">
                            <div dangerouslySetInnerHTML={{__html:editorText}}></div>
                        </Descriptions.Item>
                    </Descriptions>
                </div>
            </div>

            <div className={newsAddStyle.buttonContainer}>
                {current === stepItems.length - 1 && <span>
                    <Button type='primary' className={newsAddStyle.button} onClick={() => { handelSaveNews(0) }}>保存草稿</Button>
                    <Button danger className={newsAddStyle.button} onClick={() => { handelSaveNews(1) }}>提交审核</Button>
                </span>}
                {current < stepItems.length - 1 && <Button type='primary' className={newsAddStyle.button} onClick={() => { next() }}>下一步</Button>}
                {current > 0 && <Button type='primary' className={newsAddStyle.button} onClick={() => { prev() }}>上一步</Button>}
            </div>
        </div>

    )
}
const mapStateToProps = (state: any) => {
    return {
        categoriesList: state.StandBox.categoriesList,
        editorText: state.StandBox.editorText,
    }
}
export default connect(mapStateToProps)(NewsAdd)
